#!/usr/bin/env python3

import pymongo
import string
import sys
import os
import time
import subprocess

def func_in_utils():
    #print "func in utils"
    print("abc")

def t_sys_args(argv):
    print('args len:', len(argv))
    print('arg list:', str(argv))

def t_mongo_test(port):
    #client = pymongo.MongoClient(host='localhost', port=27017)
    client = pymongo.MongoClient('mongodb://localhost:' + port)

    db = client['db1']
    dblist = client.list_database_names()

    col = db["t"]
    collist = db.list_collection_names()
    if 't' in collist:
        print("t existed")

    student = {
        'id': '1',
        'name': 'cshi',
        'age': 20,
        'gender': 'male'
    }
    res = col.insert(student)
    print('after insert student:', res) # return new id

    r1 = {
        'k': 1,
        'v': 2
    }
    r2 = {
        'k': 2,
        'v': 3
    }
    res = col.insert([r1, r2])
    print('after insert r1, r2, res=', res)

    # 在3.x版本中，已不再推荐使用insert,而是使用insert_one, insert_many

    r3 = {
        'k': 3,
        'v': 4
    }
    r4 = {
        'k': 4,
        'v': 5
    }
    res = col.insert_many([r3, r4])
    print('after insert_many, res=', res.inserted_ids)

    res = col.find_one({'k': 1})
    print('find_one res: ', res)

    res = col.find({'v': 3})
    for r in res:
        print('find res:' , r)

    res = col.find({'v': {'$gt': 4}})
    for r in res:
        print('find gt > 4 , res:', r)

    col.find({'name': 'cshi'}).count()

    res = col.find().sort('v', pymongo.ASCENDING)
    print([r['_id'] for r in res])

    #res.skip(2)
    #res.limit(3)

    col.update({'k': 1}, {'$set': {'v': 111111111}}) # 不推荐使用，用update_one, udpate_many

    condition = {'k': 2}
    res = col.update_one(condition, {'$inc': {'v': 1}})
    print('after update_one,', res.matched_count, res.modified_count)

    col.remove({'k': 2})

    # 提供了一些组合方法
    col.find_one_and_delete({'k': 3})

def my():
    # 适用运行那种shell commands，而不是外部程序
    os.system('cat /proc/uptime')
    output = os.popen('cat /proc/uptime')
    print(output.read())

    # 官方推荐使用subprocess而不是os.system，更加灵活强大
    subprocess.call(['ls', '-l']) # after 3.5, use .run()
    subprocess.call('ls -l'.split())

    ret = subprocess.call("echo hello \$world", shell=True)

if __name__ == '__main__':
    t_sys_args(sys.argv)

    
    print('end')